<template>
	<canvas ref="treeCanvas" id="treeCanvas"></canvas>
	<button class="ex-btn" @click="exportImg">保存为图片</button>
</template>

<script setup>
import {  onMounted } from 'vue';

function exportImg() {
	const canvas = document.getElementById('treeCanvas');
	const a = document.createElement('a');
	a.href = canvas.toDataURL('image/png');
	a.download = 'tree.png';
	a.click();
}

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

function drawTree(ctx, startX, startY, len, angle, branchWidth, color1, color2) {
	ctx.beginPath();
	ctx.save();
	ctx.strokeStyle = color1;
	ctx.fillStyle = color2;
	ctx.shadowBlur = 15;
	ctx.shadowColor = 'rgba(0,0,0,0.8)';
	ctx.lineWidth = branchWidth;
	ctx.translate(startX, startY);
	ctx.rotate(angle * Math.PI / 180);
	ctx.moveTo(0, 0);
	if (angle > 0) {
		ctx.bezierCurveTo(20, -len / 2, 20, -len / 2, 0, -len);
	} else {
		ctx.bezierCurveTo(-20, -len / 2, -20, -len / 2, 0, -len);
	}
	ctx.stroke();
	
	if (len < 10) {
		ctx.beginPath();
		ctx.arc(0, -len, 10, 0, Math.PI / 2);
		ctx.fill();
		ctx.restore();
		return;
	}
	
	drawTree(ctx, 0, -len, len * 0.75, angle + getRandomInt(-10, 10), branchWidth * 0.6, color1, color2);
	drawTree(ctx, 0, -len, len * 0.75, angle + getRandomInt(-10, 10), branchWidth * 0.6, color1, color2);
	
	ctx.restore();
}

onMounted(() => {
	const canvas = document.getElementById('treeCanvas');
	console.log(canvas);
	const ctx = canvas.getContext('2d');
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	
	const drawRandomTree = (x) => {
		const startX = x;
		const startY = canvas.height;
		const len = getRandomInt(100, 200);
		const angle = 0;
		const branchWidth = getRandomInt(10, 20);
		const color1 = 'rgb(' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ')';
		const color2 = 'rgb(' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ')';
		drawTree(ctx, startX, startY, len, angle, branchWidth, color1, color2);
	}
	
	drawRandomTree(canvas.width / 2); // 初始化在中心绘制一棵树
	
	let isDrawing = false;
	
	canvas.addEventListener('click', (event) => {
		if (isDrawing) return;
		isDrawing = true;
		
		const rect = canvas.getBoundingClientRect();
		const x = event.clientX - rect.left;
		
		drawRandomTree(x);
		
		isDrawing = false;
	});
});
</script>

<style scoped lang="scss">
#treeCanvas {
	display: block;
	width: 100vw;
	height: 100vh;
}

.ex-btn {
	position: fixed;
	top: 10px;
	right: 10px;
	padding: 10px 20px;
	border-radius: 5px;
	background: #000;
	color: #fff;
	cursor: pointer;
	border: 1px solid #333;
}
</style>
